package util
{

	public class StringUtil
	{

		public static function trim(str:String):String
		{
			if(str == null || str == "")
			{
				return "";
			}
			var left:int = 0;
			var right:int = str.length - 1;

			while(str.charAt(left) == " ")
			{
				left++;
			}

			while(str.charAt(right) == " ")
			{
				right--;
			}

			if(left >= right)
			{
				return "";
			}
			return str.slice(left, right);
		}

		public static function check(str:String):Boolean
		{
			var Letters:String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890`=~!@#$%^&*()_+[]{}\\|/?.>,<;:'\-?<>/\"";
			var c:String;

			for(var i:uint = 0; i < str.length; i++)
			{
				c = str.charAt(i);

				if(Letters.indexOf(c) == -1)
				{
					return true;
				}
			}
			return false;
		}

		public static function getChar(str:String, charL:uint):String
		{
			var len:uint = 0;
			var finalStr:String = "";

			for(var i:int = 0; i < str.length; i++)
			{
				if(len >= charL)
				{
					finalStr += ".";
					return finalStr;
				}
				var mid:String = str.charAt(i);
				finalStr += mid;

				if(check(mid))
				{
					len += 2;
				}
				else
				{
					len += 1;
				}

			}
			return finalStr;
		}

		/**
		 *  使用传入的各个参数替换指定的字符串内的“{n}”标记。<br>
		 */
		public static function substitute(str:String, ... rest):String
		{
			if(str == null)
				return '';
			// Replace all of the parameters in the msg string.
			var len:uint = rest.length;
			var args:Array;

			if(len == 1 && rest[0] is Array)
			{
				args = rest[0] as Array;
				len = args.length;
			}
			else
			{
				args = rest;
			}

			for(var i:int = 0; i < len; i++)
			{
				str = str.replace(new RegExp("\\{" + i + "\\}", "g"), args[i]);
			}
			return str;
		}
	}
}